package com.hcloud.auth.resource;

import com.hcloud.auth.api.config.AbstractOAuth2ResourceServceConfig;
import com.hcloud.auth.config.SecurityConstants;
import com.hcloud.auth.sms.SmsCodeSecurityConfig;
import com.hcloud.auth.third.ThirdAuthenticationSecurityConfig;
import com.hcloud.common.core.constants.AuthConstants;
import com.hcloud.common.core.constants.ResourceConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

/**
 * 资源服务器配置
 *
 * @author hepangui
 * @date 2018-12-13
 */

@Configuration
@EnableResourceServer
public class AuthResourceServerConfig extends AbstractOAuth2ResourceServceConfig {

    @Autowired
    private ThirdAuthenticationSecurityConfig thirdAuthenticationSecurityConfig;

    @Autowired
    protected AuthenticationSuccessHandler hcloudAuthenticationSuccessHandler;

    @Autowired
    protected AuthenticationFailureHandler hcloudAuthenticationFailureHandler;

    @Autowired
    private SmsCodeSecurityConfig smsCodeSecurityConfig;

    @Override
    protected String getResourceId() {
        return ResourceConstants.AUTH;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginProcessingUrl(SecurityConstants.LOGIN_PASS)
                .successHandler(hcloudAuthenticationSuccessHandler)
                .failureHandler(hcloudAuthenticationFailureHandler);

        http    //短信验证码校验
                .apply(smsCodeSecurityConfig).and()
                //第三方登录配置
                //apply的作用就是往当前的过滤链上加过滤器,过滤器会拦截某些特定的请求,收到请求后引导用户去做社交登录
                .apply(thirdAuthenticationSecurityConfig)
                .and()
                .csrf().disable();  //防护的功能关闭

        http.authorizeRequests().antMatchers(
                SecurityConstants.LOGIN_THRID,
                SecurityConstants.MONITOR_URL).permitAll();
    }
}
